<template>
	<div class="app-container">
		<el-tabs v-model="activeName" type="card" @tab-click="handleClick">
			<el-tab-pane label="区（县）概况信息" name="first">
				<!-- 搜索 -->
				<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
					<el-form-item label="省" prop="provinceId">
						<el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" :disabled="isDisabled" clearable>
							<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="市" prop="cityId">
						<el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
							<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="区/县" prop="prefectureId">
						<el-select v-model="queryParams.prefectureId" placeholder="请选择区/县" clearable>
							<el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleQuery">搜索</el-button>
						<el-button plain @click="resetQuery">重置</el-button>
					</el-form-item>
				</el-form>

				<!-- 按钮 -->
				<el-row :gutter="10" class="mb8" style="float:left">
					<el-col :span="1.5">
						<el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button plain icon="Download" @click="handleImport(1)">导入</el-button>
					</el-col>
				</el-row>

				<div style="text-align: right;float: right;">
					<span>排列方式：</span>
					<el-radio-group v-model="queryParams.option" @change="optionChange">
						<el-radio label="0">行政区划</el-radio>
						<el-radio label="1">更新时间倒序</el-radio>
					</el-radio-group>
					<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
				</div>

				<!-- 列表 -->
				<el-table v-loading="loading" :data="dataList" stripe>
					<el-table-column label="省" align="center" prop="province" />
					<el-table-column label="市" align="center" prop="city" />
					<el-table-column label="区（县）" align="center" prop="prefecture" />
					<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
						<template #default="scope">
							<el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
							<el-button type="text" @click="handleView(scope.row)">查看</el-button>
							<el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<pagination v-show="total > 0" :total="total" v-model:page="queryParams.page"
					v-model:limit="queryParams.rows" @pagination="getList" />
			</el-tab-pane>
			<el-tab-pane label="乡镇（街道）概况信息" name="second">
				<!-- 搜索 -->
				<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
					<el-form-item label="省" prop="provinceId">
						<el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" :disabled="isDisabled" clearable>
							<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="市" prop="cityId">
						<el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
							<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="区/县" prop="prefectureId">
						<el-select v-model="queryParams.prefectureId" placeholder="请选择区/县" clearable>
							<el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="乡镇（街道）" prop="villageTown">
						<el-input v-model="queryParams.villageTown" placeholder="请输入乡镇（街道）" />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleQuery1">搜索</el-button>
						<el-button plain @click="resetQuery1">重置</el-button>
					</el-form-item>
				</el-form>

				<!-- 按钮 -->
				<el-row :gutter="10" class="mb8" style="float:left">
					<el-col :span="1.5">
						<el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
					</el-col>
					<el-col :span="1.5">
						<el-button plain icon="Download" @click="handleImport(2)">导入</el-button>
					</el-col>
				</el-row>

				<div style="text-align: right;float: right;">
					<span>排列方式：</span>
					<el-radio-group v-model="queryParams.option" @change="optionChange">
						<el-radio label="0">行政区划</el-radio>
						<el-radio label="1">更新时间倒序</el-radio>
					</el-radio-group>
					<right-toolbar v-model:showSearch="showSearch" @queryTable="getList1"></right-toolbar>
				</div>

				<!-- 列表 -->
				<el-table v-loading="loading" :data="dataList" stripe>
					<el-table-column label="省" align="center" prop="province" />
					<el-table-column label="市" align="center" prop="city" />
					<el-table-column label="区（县）" align="center" prop="prefecture" />
					<el-table-column label="乡镇（街道）" align="center" prop="villageTown" />
					<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
						<template #default="scope">
							<el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
							<el-button type="text" @click="handleView(scope.row)">查看</el-button>
							<el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<pagination v-show="total > 0" :total="total" v-model:page="queryParams.page"
					v-model:limit="queryParams.rows" @pagination="getList1" />
			</el-tab-pane>
		</el-tabs>
		<!-- 添加或修改区县概况信息 -->
		<el-dialog :title="title" v-model="showPopup" width="800px" append-to-body>
			<el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
				<p class="mt15"></p>
				<el-row>
					<el-col :span="8">
						<el-form-item label="省" prop="provinceId">
							<el-select v-model="form.provinceId" placeholder="请输入省" @change="chooseFormProvince"
								:disabled="(btnType !== 'add') || isDisabled" style="width: 100%;">
								<el-option v-for="item in provinceFormData" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="市" prop="cityId">
							<el-select v-model="form.cityId" placeholder="请输入市" @change="chooseFormCity"
								:disabled="btnType !== 'add'" style="width: 100%;">
								<el-option v-for="item in cityFormData" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="区/县" prop="prefectureId">
							<el-select v-model="form.prefectureId" placeholder="请输入区/县" :disabled="btnType !== 'add'"
								style="width: 100%;">
								<el-option v-for="item in areaFormData" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="isShowVillageTown">
					<el-col :span="14">
						<el-form-item label="乡镇（街道）" prop="villageTown">
							<el-input v-model="form.villageTown" placeholder="请输入乡镇（街道）" :disabled="btnType !== 'add'" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="地形地貌特征" prop="ccLandform">
					<el-input v-model="form.ccLandform" :disabled="btnType == 'check'" type="textarea" maxlength="500"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入地形地貌特征" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="terrainFile" :disabled="btnType == 'check'" v-model="form.ccLandformAttachment" />
				</el-form-item>
				<el-form-item label="地震构造特征" prop="ccSeismotectonics">
					<el-input v-model="form.ccSeismotectonics" type="textarea" :disabled="btnType == 'check'"
						maxlength="500" show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入地震构造特征" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="temblorFile" :disabled="btnType == 'check'"
						v-model="form.ccSeismotectonicsAttachment" />
				</el-form-item>
				<el-form-item label="气候特征" prop="ccClimate">
					<el-input v-model="form.ccClimate" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入气候特征" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="climateFile" :disabled="btnType == 'check'" v-model="form.ccClimateAttachment" />
				</el-form-item>
				<el-form-item label="人口民族特征" prop="ccNation">
					<el-input v-model="form.ccNation" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入人口民族特征" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="nationFile" :disabled="btnType == 'check'" v-model="form.ccNationAttachment" />
				</el-form-item>
				<el-form-item label="经济产业特征" prop="ccEconomy">
					<el-input v-model="form.ccEconomy" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入经济产业特征" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="economyFile" :disabled="btnType == 'check'" v-model="form.ccEconomyAttachment" />
				</el-form-item>
				<el-form-item label="交通情况" prop="ccTraffic">
					<el-input v-model="form.ccTraffic" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入交通情况" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="trafficFile" :disabled="btnType == 'check'" v-model="form.ccTrafficAttachment" />
				</el-form-item>
				<el-form-item label="地质灾害情况" prop="ccDisaster">
					<el-input v-model="form.ccDisaster" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入地质灾害情况" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="disasterFile" :disabled="btnType == 'check'" v-model="form.ccDisasterAttachment" />
				</el-form-item>
				<el-form-item label="基础设施" prop="ccFacility">
					<el-input v-model="form.ccFacility" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入基础设施" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="facilityFile" :disabled="btnType == 'check'" v-model="form.ccFacilityAttachment" />
				</el-form-item>
				<el-form-item label="历史地震情况" prop="ccHistory" v-if="isShowccHistory">
					<el-input v-model="form.ccHistory" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入历史地震情况" />
				</el-form-item>
				<el-form-item label="上传附件" v-if="isShowccHistory">
					<file-upload ref="historyFile" :disabled="btnType == 'check'" v-model="form.ccHistoryAttachment" />
				</el-form-item>
				<el-form-item label="其他区域特点" prop="ccTrait">
					<el-input v-model="form.ccTrait" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="请输入其他区域特点" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="traitFile" :disabled="btnType == 'check'" v-model="form.ccTraitAttachment" />
				</el-form-item>
				<el-form-item label="主要中小学信息统计" prop="ccSchool">
					<el-input v-model="form.ccSchool" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }"
						placeholder="包括学校名称、地址、建设年代、在校学生数、教师数、有无操场（可另附文档）" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="schoolFile" :disabled="btnType == 'check'" v-model="form.ccSchoolAttachment" />
				</el-form-item>
				<el-form-item label="主要医院信息统计" prop="ccHospital">
					<el-input v-model="form.ccHospital" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }"
						placeholder="包括主要医院名称、地址、建设年代、医院等级、医护人员数、床位数、救护车辆数（可另附文档）" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="hospitalFile" :disabled="btnType == 'check'" v-model="form.ccHospitalAttachment" />
				</el-form-item>
				<el-form-item label="重大危险源统计" prop="ccHazard">
					<el-input v-model="form.ccHazard" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }"
						placeholder="县市辖区内主要危化品存储、危化企业信息，包括名称、地址、危化品类型、规模、法人、联系方式（可另附文档）" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="hazardFile" :disabled="btnType == 'check'" v-model="form.ccHazardAttachment" />
				</el-form-item>
				<el-form-item label="水库信息统计" prop="ccReservoir">
					<el-input v-model="form.ccReservoir" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }"
						placeholder="包括水库名称、地址、库容、坝体类型、建设年代、设防标准、淹没区范围等（可另附文档）" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="reservoirFile" :disabled="btnType == 'check'" v-model="form.ccReservoirAttachment" />
				</el-form-item>
				<el-form-item label="综合信息" prop="ccMessage">
					<el-input v-model="form.ccMessage" type="textarea" maxlength="500" :disabled="btnType == 'check'"
						show-word-limit :autosize="{ minRows: 4, maxRows: 5 }" placeholder="县市地方统计年鉴、地方县志等资料（可另附文档）" />
				</el-form-item>
				<el-form-item label="上传附件">
					<file-upload ref="messageFile" :disabled="btnType == 'check'" v-model="form.ccMessageAttachment" />
				</el-form-item>

			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm" v-show="btnType !== 'check'">确 定</el-button>
					<el-button plain @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 导入对话框 -->
		<el-dialog :title="upload.title" v-if="upload.open" v-model="upload.open" width="400px" append-to-body>
			<p></p>
			<el-upload ref="uploadRef" :limit="1" :accept="['.xls', '.xlsx']" :headers="upload.headers"
				:action="name == '区县综合概况信息.xls' ? upload.url : upload.url1" :disabled="upload.isUploading"
				:before-upload="handleFileBeforeUpload" :on-progress="handleFileUploadProgress"
				:on-error="handleFileUploadError" :on-success="handleFileSuccess" :auto-upload="false" drag>
				<el-icon class="el-icon--upload"><upload-filled /></el-icon>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<template #tip>
					<div class="el-upload__tip text-center">
						<span>仅允许导入xls格式文件。</span>
						<el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
							@click="importTemplate(name)">下载模板</el-link>
					</div>
				</template>
			</el-upload>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitFileForm">确 定</el-button>
					<el-button plain @click="upload.open = false">取 消</el-button>
				</div>
			</template>
		</el-dialog>

	</div>
</template>

<script setup name="areaCountyOverview">
import { getAllCountiesCondition, getAllVillageTownCondition, saveCountiesCondition, saveVillageTownCondition, getCountiesCondition, getVillageTownCondition, delCountiesCondition, delVillageTownCondition, updateCountiesCondition, updateVillageTownCondition, coverCountiesCondition, coverVillageTownCondition } from "@/api/basedatamanage/areaCounty.js";
import { getProvince, getChildArea } from "@/api/system/division";
import { getLanderRoles, getLanderProvince } from "@/api/basedatamanage/common.js"
import { getToken } from "@/utils/auth";
import { ElMessageBox } from 'element-plus'
import { on } from "events";
const { proxy } = getCurrentInstance();
const activeName = ref("first");
const dataList = ref([]); //列表
const loading = ref(false); //加载状态
const btnType = ref(""); //按钮状态
const showPopup = ref(false); // 弹框
const isShowVillageTown = ref(false); // 是否展示乡镇（街道）
const isShowccHistory = ref(true); // 是否展示历史地震情况
const total = ref(0); //列表总条数
const title = ref(""); //弹框title
const showSearch = ref(true); //是否显示搜索项
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
const provinceFormData = ref([]); //表单省 
const cityFormData = ref([]); //表单市
const areaFormData = ref([]); //表单区、县
const name = ref(''); // 模版名字
const data = reactive({
	queryParams: {
		page: 1,
		rows: 10,
		provinceId: null,
		cityId: null,
		areaId: null,
		option: '0'
	},
	form: {},
	rules: {
		provinceId: [{
			required: true,
			message: '请选择省',
			trigger: 'blur'
		}],
		cityId: [{
			required: true,
			message: '请选择市',
			trigger: 'blur'
		}],
		prefectureId: [{
			required: true,
			message: '请选择区/县',
			trigger: 'blur'
		}],
		villageTown: [{
			required: true,
			message: '请输入乡镇（街道）',
			trigger: 'blur'
		}],
		ccLandform: [{
			required: true,
			message: '请输入地貌地形特征',
			trigger: 'blur'
		}],
		ccSeismotectonics: [{
			required: true,
			message: '请输入地震构造特征',
			trigger: 'blur'
		}],
		ccClimate: [{
			required: true,
			message: '请输入气候特征',
			trigger: 'blur'
		}],
		ccNation: [{
			required: true,
			message: '请输入人口民族特性',
			trigger: 'blur'
		}],
		ccEconomy: [{
			required: true,
			message: '请输入经济产业特性',
			trigger: 'blur'
		}],
		ccTraffic: [{
			required: true,
			message: '请输入交通情况',
			trigger: 'blur'
		}],
		ccDisaster: [{
			required: true,
			message: '请输入地质灾害情况',
			trigger: 'blur'
		}],
		ccFacility: [{
			required: true,
			message: '请输入基础设施',
			trigger: 'blur'
		}],
		ccHistory: [{
			required: true,
			message: '请输入历史地震情况',
			trigger: 'blur'
		}],
		ccTrait: [{
			required: true,
			message: '请输入其他区域特点',
			trigger: 'blur'
		}],
		ccSchool: [{
			required: true,
			message: '请输入主要中小学信息统计',
			trigger: 'blur'
		}],
		ccHospital: [{
			required: true,
			message: '请输入主要医院信息统计',
			trigger: 'blur'
		}],
		ccHazard: [{
			required: true,
			message: '请输入重大危险源统计',
			trigger: 'blur'
		}],
		ccReservoir: [{
			required: true,
			message: '请输入水库信息统计',
			trigger: 'blur'
		}],
		ccMessage: [{
			required: true,
			message: '请输入综合信息',
			trigger: 'blur'
		}],

	}
})
const {
	queryParams,
	form,
	rules
} = toRefs(data)
const isDisabled = ref(false)

/*** 导入参数 */
const upload = reactive({
	open: false,
	title: "",
	isUploading: false,
	headers: { token: "token " + getToken() },
	url: import.meta.env.VITE_APP_BASE_API + "/fxfzypg/baseData/importExcelCountiesCondition",
	url1: import.meta.env.VITE_APP_BASE_API + "/fxfzypg/baseData/villageTown/importExcelVillageTownCondition"
});

// 模板下载
function importTemplate(name) {
	proxy.download("/base/product/downloadExcel", {
		fileName: name
	}, name);
};

/** 提交上传文件 */
function submitFileForm() {
	proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport(num) {
	if (num == 1) {
		name.value = '区县综合概况信息.xls';
	} else {
		name.value = '乡镇（街道）综合概况信息.xls';
	}
	upload.title = "导入";
	upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
	proxy.$modal.loading("正在上传文件，请稍候...");
	return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
	upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
	proxy.$modal.closeLoading();
	proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
	upload.open = false;
	upload.isUploading = false;
	proxy.$modal.closeLoading();
	proxy.$refs["uploadRef"].handleRemove(file);
	if (response.code == 500) {
		ElMessageBox.alert(response.message, '消息', {
			type: 'warning',
			confirmButtonText: '确定',
			dangerouslyUseHTMLString: true,
			callback: () => {
			},
		})
	} else {
		if (response.data) {
			ElMessageBox.confirm(
				response.message,
				'消息',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					dangerouslyUseHTMLString: true,
					cancelButtonClass: 'is-plain',
				}
			)
				.then(() => {
					if (activeName.value == 'first') {
						coverCountiesCondition(response.data).then(res => {
							proxy.$modal.msgSuccess(res.data);
							getList();
						})
					} else {
						coverVillageTownCondition(response.data).then(res => {
							proxy.$modal.msgSuccess(res.data);
							getList1();
						})
					}
				})
				.catch(() => {
					// ElMessage({
					// 	type: 'info',
					// 	message: 'Delete canceled',
					// })
				})
		} else {
			ElMessageBox.alert(response.message, '消息', {
				type: 'success',
				confirmButtonText: '确定',
				dangerouslyUseHTMLString: true,
				callback: () => {
					if (activeName.value == 'first') {
						getList();
					} else {
						getList1();
					}
				},
			})
		}
	}
};

/** 查询区县概况列表 */
function getList() {
	loading.value = true;
	getAllCountiesCondition(queryParams.value).then(response => {
		dataList.value = response.data.rows;;
		total.value = response.data.total;
		loading.value = false;
	});
}
/** 查询乡镇（街道）概况信息列表 */
function getList1() {
	loading.value = true;
	getAllVillageTownCondition(queryParams.value).then(response => {
		dataList.value = response.data.rows;;
		total.value = response.data.total;
		loading.value = false;
	});
}
/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.page = 1;
	getList();
}
/** 搜索按钮操作 */
function handleQuery1() {
	queryParams.value.page = 1;
	getList1();
}
/** 重置按钮操作 */
function resetQuery() {
	dataList.value = [];
	proxy.resetForm("queryRef");
	queryParams.value.page = 1;
	getDefaultProvice()
}
/** 重置按钮操作 */
function resetQuery1() {
	dataList.value = [];
	proxy.resetForm("queryRef");
	queryParams.value.page = 1;
	getDefaultProvice()
}
// 切换排序
function optionChange(val) {
	if (activeName.value == 'first') {
		handleQuery()
	} else if (activeName.value == 'second') {
		handleQuery1()
	}
}
// 重置表单
function reset() {
	form.value = {
		province: '',
		city: '',
		prefecture: '',
		gdp: '',
		peoAvgGdp: '',
	}
	proxy.resetForm("ruleForm");
	console.log(proxy)
}

/** 取消按钮 */
function cancel() {
	showPopup.value = false;
	reset();
};
/** 新增按钮操作 */
function handleAdd() {
	reset();
	btnType.value = 'add';
	showPopup.value = true;
	if (!isShowVillageTown.value) {
		title.value = "添加区县概况信息";
	} else {
		title.value = "添加乡镇（街道）概况信息";
	}
	if(isDisabled.value){
		form.value.provinceId = queryParams.value.provinceId;
		chooseFormProvince(form.value.provinceId);
	}
	getProvinceFormData();
}

/** 修改按钮操作 */
function handleUpdate(row) {
	reset();
	btnType.value = 'edit';
	const id = row.ccId || ''
	if (!isShowVillageTown.value) {
		getCountiesCondition(id).then(response => {
			editProvinceFormData(response.data.provinceId, response.data.cityId)
			form.value = {
				...response.data
			};
			form.value.id = response.data.ccId;
			showPopup.value = true;
			title.value = "修改区县概况信息";
		});
	} else {
		getVillageTownCondition(id).then(response => {
			editProvinceFormData(response.data.provinceId, response.data.cityId)
			form.value = {
				...response.data
			};
			form.value.id = response.data.ccId;
			showPopup.value = true;
			title.value = "修改乡镇（街道）概况信息";
		});
	}

}

/** 查看按钮操作 */
function handleView(row) {
	reset();
	btnType.value = 'check';
	const id = row.ccId || ''
	if (!isShowVillageTown.value) {
		getCountiesCondition(id).then(response => {
			editProvinceFormData(response.data.provinceId, response.data.cityId);
			form.value = {
				...response.data
			};
			form.value.id = response.data.ccId;
			showPopup.value = true;
			title.value = "查看区县概况信息";
		});
	} else {
		getVillageTownCondition(id).then(response => {
			editProvinceFormData(response.data.provinceId, response.data.cityId);
			form.value = {
				...response.data
			};
			form.value.id = response.data.ccId;
			showPopup.value = true;
			title.value = "查看乡镇（街道）概况信息";
		});
	}

}

//修改后省市区赋值
function editProvinceFormData(provinceId, cityId) {
	getProvince().then(response => {
		provinceFormData.value = response.data;
	});
	getChildArea(provinceId).then(response => {
		cityFormData.value = response.data;
	});
	getChildArea(cityId).then(response => {
		areaFormData.value = response.data;
	});
}

/** 删除按钮操作 */
function handleDelete(row) {
	const ids = row.ccId || '';
	if (!isShowVillageTown.value) {
		proxy.$modal.confirm('是否确认删除区县概况信息为"' + row.province + row.city + row.prefecture + '"的数据项？').then(function () {
			return delCountiesCondition(ids);
		}).then(() => {
			getList();
			proxy.$modal.msgSuccess("删除成功");
		}).catch(() => { });
	} else {
		proxy.$modal.confirm('是否确认删除乡镇（街道）概况信息为"' + row.province + row.city + row.prefecture + row.villageTown + '"的数据项？').then(function () {
			return delVillageTownCondition(ids);
		}).then(() => {
			getList1();
			proxy.$modal.msgSuccess("删除成功");
		}).catch(() => { });
	}

}

//处理附件格式
function eachFiles(fileName) {
	let deepFile = JSON.parse(JSON.stringify(proxy.$refs[fileName].fileList))
	let Ids = []
	for (var i = 0; i < deepFile.length; i++) {
		Ids.push(deepFile[i].attachId)
	}
	return Ids.join(",");
}

/** 提交按钮 */
function submitForm() {
	// 处理附件
	if (!isShowVillageTown.value) {
		form.value.ccHistoryAttachment = eachFiles('historyFile');
	}
	form.value.ccLandformAttachment = eachFiles('terrainFile');
	form.value.ccSeismotectonicsAttachment = eachFiles('temblorFile');
	form.value.ccClimateAttachment = eachFiles('climateFile');
	form.value.ccNationAttachment = eachFiles('nationFile');
	form.value.ccEconomyAttachment = eachFiles('economyFile');
	form.value.ccTrafficAttachment = eachFiles('trafficFile');
	form.value.ccDisasterAttachment = eachFiles('disasterFile');
	form.value.ccFacilityAttachment = eachFiles('facilityFile');

	form.value.ccTraitAttachment = eachFiles('traitFile');
	form.value.ccSchoolAttachment = eachFiles('schoolFile');
	form.value.ccHospitalAttachment = eachFiles('hospitalFile');
	form.value.ccHazardAttachment = eachFiles('hazardFile');
	form.value.ccReservoirAttachment = eachFiles('reservoirFile');
	form.value.ccMessageAttachment = eachFiles('messageFile');
	console.log(form)
	if (!isShowVillageTown.value) {
		proxy.$refs["ruleForm"].validate(valid => {
			if (valid) {
				if (form.value.id != null) {
					updateCountiesCondition(form.value).then(response => {
						proxy.$modal.msgSuccess("修改成功");
						showPopup.value = false;
						getList();
					});
				} else {
					saveCountiesCondition(form.value).then(response => {
						proxy.$modal.msgSuccess("新增成功");
						showPopup.value = false;
						handleQuery();
					});
				}
			}
		});
	} else {
		proxy.$refs["ruleForm"].validate(valid => {
			if (valid) {
				if (form.value.id != null) {
					updateVillageTownCondition(form.value).then(response => {
						proxy.$modal.msgSuccess("修改成功");
						showPopup.value = false;
						getList1();
					});
				} else {
					saveVillageTownCondition(form.value).then(response => {
						proxy.$modal.msgSuccess("新增成功");
						showPopup.value = false;
						handleQuery1();
					});
				}
			}
		});
	}

}

/** 搜索获取省市列表Start */
function getProvinceData() {
	getProvince().then(response => {
		provinceData.value = response.data;
	});
}

function chooseProvince(value) {
	queryParams.value.cityId = null;
	queryParams.value.areaId = null;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value).then(response => {
		cityData.value = response.data;
	});
}

function chooseCity(value) {
	queryParams.value.areaId = null;
	areaData.value = [];
	getChildArea(value).then(response => {
		areaData.value = response.data;
	});
}
/** 搜索获取省市列表End */

/** 表单搜索获取省市列表Start */
function chooseFormProvince(value) {
	form.value.city = null;
	form.value.area = null;
	cityFormData.value = [];
	areaFormData.value = [];
	getChildArea(value).then(response => {
		cityFormData.value = response.data;
	});
}

function chooseFormCity(value) {
	form.value.area = null;
	areaFormData.value = [];
	getChildArea(value).then(response => {
		areaFormData.value = response.data;
	});
}

function getProvinceFormData() {
	getProvince().then(response => {
		provinceFormData.value = response.data;
	});
}
/*切换标签页*/
function handleClick(tab, event) {
	console.log(tab.props.name);
	if (tab.props.name == "first") {
		handleQuery();
		isShowVillageTown.value = false;
		isShowccHistory.value = true;
	} else {
		handleQuery1();
		isShowVillageTown.value = true;
		isShowccHistory.value = false;
	}
}
// 权限
const isAdmin = async () => {
	let res = await getLanderRoles()
	const { code, data } = res
	if (code == 200) {
		const auth = data.split(',')
		return auth
	} else {
		return Promise.reject(new Error(data))
	}
}

const getDefaultProvice = async () => {
	try {
		let curAuth = await isAdmin()
		const type1 = curAuth.length == 1 && (curAuth.includes('省管理员') || curAuth.includes('省业务员'))
		const type2 = curAuth.length == 2 && curAuth.includes('省管理员') && curAuth.includes('省业务员')
		if (type1 || type2) {
			getLanderProvince().then(res => {
				if (res.code == 200) {
					isDisabled.value = true
					queryParams.value.provinceId = res.data
					chooseProvince(queryParams.value.provinceId)
					if(activeName.value == 'first'){
						getList()
					}else{
						getList1()
					}
				}
			})
		} else {
			isDisabled.value = false
			if(activeName.value == 'first'){
				getList()
			}else{
				getList1()
			}
		}
	} catch (error) {

	}
}
onMounted(async() => {
	await getProvinceData();
	await getDefaultProvice();
})
</script>

<style lang="scss" scoped>
.mt15 {
	margin-top: 15px;
}
</style>